const moment = require('moment');
const schema =  require('../conf/schema');
const ObjectID = require('mongodb').ObjectID;
const config = require('../conf/app').userConfig;

const User = schema.user;

const user = {
    saveUserInfo: function (userInfo, session_key, skey) {
        const uid = userInfo.openId,
            create_time = moment().format('YYYY-MM-DD HH:mm:ss'),
            update_time = create_time;
        const insertObj = {
            'uid': uid,
            'create_time': create_time,
            'uname': userInfo.nickName,
            'ugender': userInfo.gender,
            'uaddress': userInfo.province+','+userInfo.country,
            'update_time': update_time,
            'ubalance': config.credit,
            'skey': skey,
            'sessionkey': session_key,
            'uavatar': userInfo.avatarUrl
        };
        const updateObj = {
            'uname': userInfo.nickName,
            'ugender': userInfo.gender,
            'uaddress': userInfo.province + ',' + userInfo.country,
            'update_time': update_time,
            'skey': skey,
            'sessionkey': session_key,
            'uavatar': userInfo.avatarUrl
        };
        let ubalance;

        return User.findOne({uid : uid}, function (err, re) {
                if (err) {
                    return ERR(500, err);
                } else {
                    if(re!=null) {
                        console.log("Fecth info: " + re );

                        return re;
                    } else {
                      return null;
                    }
                }
            })
            .then(function(res) {
                
                if (res && res.uid==uid) {         // 已经有此用户，则更新用户信息
                    console.log("update user: ", res);
                    ubalance = res.ubalance;
                    User.update({uid: uid}, updateObj);
                    return res;

                } else {                        // 否则，添加此用户
                    console.log("create user: ", res);
                    ubalance = config.credit;
                    const user = new User({
                      uid: uid,
                      create_time: create_time,
                      uname: userInfo.nickName,
                      ugender: userInfo.gender,
                      uaddress: userInfo.province+','+userInfo.country,
                      update_time: update_time,
                      ubalance: config.credit,
                      skey: skey,
                      sessionkey: session_key,
                      uavatar: userInfo.avatarUrl
                    });

                    return user.save();
                }
            })
            .then(function (res) {
                console.log("user info: ", res);
                const resUserObj = Object.assign({}, userInfo, { balance: ubalance, uid: res._id});
                delete resUserObj.openId && delete resUserObj.watermark;
                return {
                    userInfo: resUserObj,
                    skey: skey
                }
            })
            .catch(function(e) {
                console.log('save userInfo error', JSON.stringify(e));
                return {
                    errmsg: JSON.stringify(e)
                }
            })
    },
    getBoughtBooks: function (skey) {
        // return {_.query($sqlQuery.getBoughtBooks, skey)};
        return {};
    },
    getUserBalance: function (skey) {
        // return _.query($sqlQuery.getBalance, skey);
        return User.findOne({skey : skey}, function (err, re) {
            if (err) {
                console.error(err);
                return 500;
            } else {
                if(re!=null) {
                    console.log("Fecth info: " + re );

                    return re;
                } else {
                  return 501;
                }
            }
        });
    },
    getUserId: function (skey,content) {
        // return _.query($sqlQuery.getId, [skey,content]);
        return {};
    }
};

module.exports = user;
